<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入饮料名称" suffix-icon="el-icon-search" v-model="milkteaName"></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
      <el-button type="info" v-if="whetherOnlyShowListedCommodities" @click="showAllCommodities">显示所有商品</el-button>
      <el-button type="success" v-if="!whetherOnlyShowListedCommodities" @click="onlyShowListedCommodities">显示上架商品</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd(null)">添加饮料 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量下架这些商品吗？"
          @confirm="delistBatch"
      >
        <el-button type="danger" slot="reference">批量下架 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="milkteaName" label="饮料名称"></el-table-column>
      <el-table-column prop="price" label="价格（单位：元）"></el-table-column>
      <!--      <el-table-column prop="description" label="描述"></el-table-column>-->
      <!--      <el-table-column prop="imageUrl" label="图片URL"></el-table-column>-->
      <!--      <el-table-column prop="ingredients" label="原料"></el-table-column>-->
      <el-table-column label="是否上架">
        <template slot-scope="scope">
          <span>{{ scope.row.whetherToList ? '是' : '否' }}</span>
        </template>
      </el-table-column>


      <el-table-column label="商品详情" width="78">
        <template slot-scope="scope">
          <el-button type="primary" @click="showDetailDialog(scope.row)">查看</el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作"  align="center">
        <template slot-scope="scope">
          <el-button type="success" v-if="scope.row.whetherToList" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
          <!--          <el-upload-->
          <!--              :action="'http://' + sharedFilesModuleServerSocket + '/shared/files/upload'"-->
          <!--              :show-file-list="false"-->
          <!--              :data="{ id: scope.row.id }"-->
          <!--              :on-success="handleImageUploadSuccess"-->
          <!--              :before-upload="beforeImageUpload"-->

          <!--              style="display: inline-block; margin-right: 8px;"-->
          <!--          >-->
          <!--            <el-button type="primary" class="ml-5">添加饮料图片 <i class="el-icon-top"></i></el-button>-->
          <!--          </el-upload>-->
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定下架吗？"
              @confirm="delist(scope.row.id)"
          >
            <el-button type="danger" slot="reference" v-if="scope.row.whetherToList">下架 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
          <el-button type="primary" slot="reference" v-if="!scope.row.whetherToList"  @click="handleEdit(scope.row)">重新上架 <i class="el-icon-circle-plus-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="饮料信息" :visible.sync="dialogFormVisible" width="30%" >
      <el-form label-width="80px" size="small">
        <el-form-item label="名称">
          <el-input v-model="form.milkteaName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="原料">-->
        <!--          <el-select-->
        <!--              v-model="selectedIngredients"-->
        <!--              multiple-->
        <!--              placeholder="请选择原料"-->
        <!--              @change="updateIngredients">-->
        <!--            <el-option label="椰子水" value="1"></el-option>-->
        <!--            <el-option label="牛奶" value="2"></el-option>-->
        <!--            <el-option label="气泡水" value="3"></el-option>-->
        <!--            <el-option label="可乐" value="4"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="原料">
          <el-select
              v-model="selectedIngredients"
              multiple
              placeholder="请选择原料"
              @change="updateSelectedIngredients">
            <el-option label="椰汁" value="椰汁"></el-option>
            <el-option label="牛奶" value="牛奶"></el-option>
            <el-option label="气泡水" value="气泡水"></el-option>
            <el-option label="可乐" value="可乐"></el-option>
            <el-option label="橙汁" value="橙汁"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="碳酸饮料" value="碳酸饮料"></el-option>
            <el-option label="奶茶" value="奶茶"></el-option>
            <el-option label="果茶" value="果茶"></el-option>
            <el-option label="圣代" value="圣代"></el-option>
          </el-select>
        </el-form-item>
        <<el-form-item label="上传图片">
        <el-upload
            class="upload-demo"
            :action="'http://' + sharedFilesModuleServerSocket + '/shared/files/upload'"
            :on-success="handleUploadSuccess"
            :before-upload="beforeImageUpload"
            accept="image/*"
            :show-file-list="false">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
        <el-form-item label="预览图">
          <img v-if="uploadedImageUrl" :src="uploadedImageUrl" alt="Uploaded Image" style="max-width: 100%; max-height: 200px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!--    <el-dialog title="添加饮料" :visible.sync="addDialogFormVisible" width="30%" >-->
    <!--      <el-form label-width="80px" size="small">-->
    <!--        &lt;!&ndash;        <el-form-item label="选择饮料">&ndash;&gt;-->
    <!--        &lt;!&ndash;          <el-select v-model="form.classId" clearable placeholder="请选择">&ndash;&gt;-->
    <!--        &lt;!&ndash;            <el-option v-for="item in filteredClassesList" :key="item.classId" :label="item.className" :value="item.classId"></el-option>&ndash;&gt;-->
    <!--        &lt;!&ndash;          </el-select>&ndash;&gt;-->
    <!--        &lt;!&ndash;        </el-form-item>&ndash;&gt;-->

    <!--      </el-form>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="addDialogFormVisible = false">取 消</el-button>-->
    <!--        <el-button type="primary" @click="add">确 定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->

    <!--    <el-dialog title="新建饮料" :visible.sync="buildDialogFormVisible" width="30%" >-->
    <!--      <el-form label-width="80px" size="small">-->
    <!--        <el-form-item label="饮料名称">-->
    <!--          <el-input v-model="form.milkteaName" autocomplete="off"></el-input>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="buildDialogFormVisible = false">取 消</el-button>-->
    <!--        <el-button type="primary" @click="save">确 定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->

    <el-dialog title="饮料详情" :visible.sync="dialogDetailVisible" width="50%">
      <div style="width: 100%; height: 200px; overflow: hidden;">
        <img :src="selectedRow.imageUrl" alt="饮料" style="width: 100%; height: 100%; object-fit: contain;" />
      </div>
      <div style="margin-top: 10px;">
        <span>饮料名称：</span>
        <span>{{ selectedRow.milkteaName }}</span>
      </div>
      <div style="margin-top: 10px;">
        <span>描述：</span>
        <pre>
          <span class="description-span">{{ selectedRow.description }}</span>
        </pre>
      </div>
      <div style="margin-top: 10px;">
        <span>原料：</span>
        <div>
          <el-tag
              v-for="ingredient in selectedRow.ingredients"
              :key="ingredient"
              style="margin-right: 5px;">
            {{ ingredient }}
          </el-tag>
        </div>
      </div>
      <div style="margin-top: 10px;">
        <span>类型：</span>
        <span>{{ selectedRow.type }}</span>
      </div>
      <div style="margin-top: 10px;">
        <span>价格：</span>
        <span>{{ selectedRow.price }} 元</span>
      </div>
      <div v-if="!selectedRow.whetherToList" style="display: flex; justify-content: flex-end; margin-top: 10px;">
        <img src="http://127.0.0.1:8099/shared/files/67fcc60a50204b43a0166a27b907fe21.png" alt="已下架提示" style="max-width: 200px;">
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {defineComponent} from "vue";
import request from "@/utils/request";
import _ from 'lodash';
import axios from "axios";
import {sharedFilesModuleServerSocket} from "../../public/config";

export default defineComponent({
  name: "Commodities",
  data(){
    return{
      sharedFilesModuleServerSocket: sharedFilesModuleServerSocket,

      lastSearchParams: {}, // 新增用于存储上一次搜索参数的对象
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,

      type: 0,
      milkteaName: "",

      // form: {
      //   name: '',
      //   price: '',
      //   imageId: null, // 新增字段
      // },
      form: {},
      uploadedImageUrl: '',
      dialogFormVisible: false,
      selectedRow: {},
      dialogDetailVisible: false,

      selectedIngredients: [],
      whetherOnlyShowListedCommodities: true,

      // addDialogFormVisible: false,
      // buildDialogFormVisible: false,
      multipleSelection: [],
      teacher: localStorage.getItem("individual") ? JSON.parse(localStorage.getItem("individual")) : {}
    }
  },
  computed: {

  },
  created() {
    // 请求分页查询数据
    this.load()
  },
  methods:{
    load() {
      // 比较当前搜索参数与上一次搜索参数
      const currentParams = {
        milkteaName: this.milkteaName,
        pageSize:this.pageSize
      };
      if (!_.isEqual(currentParams, this.lastSearchParams)) {
        this.pageNum = 1; // 如果参数不同，重置页码
        this.lastSearchParams = { ...currentParams }; // 更新上一次搜索参数
      };

      this.request.get("/merchant/commodities/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          type: this.type,
          milkteaName: this.milkteaName,
          whetherOnlyShowListedCommodities: this.whetherOnlyShowListedCommodities
        }
      }).then(res => {
        console.log(res);
        this.tableData = res.data.records;
        this.total = res.data.total;
      }).catch(error => {
        console.error("Error fetching data:", error);
      });

    },
    showAllCommodities(){
      this.whetherOnlyShowListedCommodities = false;
      this.load();
    },
    onlyShowListedCommodities(){
      this.whetherOnlyShowListedCommodities = true;
      this.load();
    },
    // add() {
    //   // const formDataWithTeacherId = { ...this.form, teacherId: this.teacher.id };
    //   this.request.get("/class/add", {
    //     params: {
    //       classId: this.form.classId,
    //       teacherId: this.teacher.id,
    //     }
    //   }).then(res => {
    //     if (res) {
    //       this.$message.success("添加成功")
    //       this.addDialogFormVisible = false
    //       this.load()
    //     } else {
    //       this.$message.error("添加失败")
    //     }
    //   })
    // },
    // save() {
    //   const formData = {
    //     class: this.form,
    //     teacherId: this.teacher.id
    //   };
    //   console.log(formData);
    //   this.request.post("/class", formData).then(res => {
    //     if (res.code === '200') {
    //       this.$message.success("保存成功")
    //       this.buildDialogFormVisible = false
    //       this.load()
    //     } else {
    //       this.$message.error("保存失败")
    //     }
    //   })
    // },
    save() {

      if(!this.form.milkteaName){
        this.$message.error("商品名称不能为空！");
        return;
      }

      // 检查 price 是否为浮点数
      const price = parseFloat(this.form.price);
      if (isNaN(price) || !isFinite(price)) {
        this.$message.error("填写的价格必须是有效的浮点数！");
        return;
      }

      // 检查 imageId 是否为空
      if (!this.form.imageId) {
        this.$message.error("图片未上传！");
        return;
      }

      if(this.selectedIngredients.length>0){
        const ingredientMap = {
          '椰汁': 1,
          '牛奶': 2,
          '气泡水': 3,
          '可乐': 4,
          '橙汁': 5
        };
        this.form.ingredients = this.selectedIngredients.map(ingredient => ingredientMap[ingredient]).join(',');
        this.selectedIngredients = [];
      }else {
        this.$message.error("未选择原料！");
        return;
      }

      if(this.form.type){
        switch (this.form.type){
          case "碳酸饮料":
            this.form.type = 1;
            break;
          case "奶茶":
            this.form.type = 2;
            break;
          case "果茶":
            this.form.type = 3;
            break;
          case "圣代":
            this.form.type = 4;
            break;
        }
      }else {
        this.$message.error("饮料类型未设置！");
        return;
      }

      this.form.whetherToList = true;

      this.request.post("/merchant/commodities", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    },

    updateSelectedIngredients() {
      // 此处可以进行任何额外的逻辑处理
      console.log(this.selectedIngredients); // 或者其他处理
    },

    handleAdd() {
      this.dialogFormVisible = true;
      // this.form = { name: '', price: '', imageId: null }; // 重置表单
      this.form = {};
      this.uploadedImageUrl = '';
      this.selectedIngredients = [];
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.uploadedImageUrl = this.form.imageUrl;
      delete this.form.imageUrl;
      this.selectedIngredients = this.form.ingredients;


      console.log("this.selectedIngredients: "+this.selectedIngredients)
      // console.log("this.form.type: "+this.form.type)

      this.dialogFormVisible = true;
    },

    showDetailDialog(row) {
      this.selectedRow = row; // 将当前行的数据存储在 selectedRow 中
      this.dialogDetailVisible = true; // 显示对话框
    },
    // handleBuild(){
    //   this.buildDialogFormVisible = true
    //   this.form = {}
    // },


    delist(id) {
      this.request.delete("/merchant/commodities/" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("下架成功")
          this.load()
        } else {
          this.$message.error("下架失败")
        }
      })
    },

    // relist(id) {
    //   this.request.get("/merchant/commodities/relist/" + id).then(res => {
    //     if (res.code === '200') {
    //       this.$message.success("上架成功")
    //       this.load()
    //     } else {
    //       this.$message.error("上架失败")
    //     }
    //   })
    // },

    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delistBatch() {
      let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
      this.request.post("/merchant/commodities/delist/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success("批量下架成功")
          this.load()
        } else {
          this.$message.error("批量下架失败")
        }
      })
    },
    reset() {
      this.milkteaName = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    // handleManageStudents(classId, milkteaName) {
    //   const encodedMilkName = encodeURIComponent(milkteaName);
    //   this.$router.push({ path: '/student', query: { classId: classId, milkteaName: encodedMilkName } });
    // },
    // handleManageCurricula(classId, milkteaName){
    //   const encodedMilkName = encodeURIComponent(milkteaName);
    //   this.$router.push({ path: '/curricula', query: { classId: classId, milkteaName: encodedMilkName } });
    // }

    // handleImageUploadSuccess(res) {
    //   console.log(res)
    //   this.$message.success("上传成功")
    //   this.load()
    // },
    // handleUploadSuccess(response) {
    //   // 假设接口返回的 ID 在 response 中的 fileId 字段
    //   this.form.imageId = response; // 将返回的 ID 存储到 form 中
    // },
    getImageUrl(imageId) {
      this.request.get("/shared/files/url/"+imageId, { responseType: 'text' })
          .then(res => {
            this.uploadedImageUrl = res.data;
          })
          .catch(error => {
            console.error('获取图片 URL 失败:', error);
          });
    },
    handleUploadSuccess(response) {
      this.form.imageId = response;
      this.getImageUrl(response);
    },
    beforeImageUpload(file) {
      // 检查文件类型是否为PNG或JPG
      const isAllowedType = file.type === 'image/png' || file.type === 'image/jpeg';
      // 检查文件大小是否小于100MB
      const isLt100M = file.size / 1024 / 1024 < 100;

      if (!isAllowedType) {
        this.$message.error('上传文件必须是PNG或JPG格式。');
        return false;
      }
      if (!isLt100M) {
        this.$message.error('上传的图片大小不能超过 100MB。');
        return false;
      }
      return true;
    },

    // beforeUpload(file) {
    //   const isImage = file.type.startsWith('image/');
    //   if (!isImage) {
    //     this.$message.error('上传文件必须是图片！');
    //   }
    //   return isImage;
    // }


  }
})
</script>


<style>
.headerBg {
  background: #eee!important;
}
.fontSize18{
  font-size: 18px;
}
.fontSize12{
  font-size: 12px;
}
.description-span {
  white-space: pre-wrap; /* 或者使用 pre-line */
  word-wrap: break-word;
}
</style>
